package com.example.privacy;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.privacy.Utils.SharedPreferencesUtils;
import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity {

    private TextView tv;
    private EditText etusername;
    private EditText etpassword;
    private Button login_button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        tv = (TextView)findViewById(R.id.go_register);
        etusername = (EditText)findViewById(R.id.login_input_username);
        etpassword = (EditText)findViewById(R.id.login_input_password);
        login_button = (Button)findViewById(R.id.login_button);
        register_go_help();
        login_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                doLogin();
            }
        });
    }

    //成功就保存Token和username password
    //不成功就不保存其中的内容或者是将内容置空
    //主要是根据返回的http状态和内容判断
    private void doLogin(){
        String username = etusername.getText().toString();
        String password = etpassword.getText().toString();
        if(username==null||username.equals("")){
            Toast.makeText(this,"请输入用户名",Toast.LENGTH_SHORT).show();
            return;
        }
        if(password==null||password.equals("")){
            Toast.makeText(this,"请输入密码",Toast.LENGTH_SHORT).show();
            return;
        }
        Authenticate(username,password);
    }


    private void Authenticate(final String username, final String password){
        new Thread(new Runnable() {
            @Override
            public void run() {
                final MediaType JSON = MediaType.get("application/json; charset=utf-8");
                String url = getString(R.string.baseUrl)+"/authenticate";
                System.out.println(url);
                final OkHttpClient client = new OkHttpClient();
                String json = String.format("{\"username\":\"%s\",\"password\":\"%s\"}", username,password);
                System.out.println(json);
                RequestBody body = RequestBody.create(json, JSON);
                System.out.println(body.toString());
                final Request request = new Request.Builder()
                        .url(url)
                        .post(body)
                        .build();
                System.out.println("运行");
                try {
                    //判断请求是否成功，也就是判断登录是否成功
                    Response response = client.newCall(request).execute();
                    System.out.println("运行1");
                    if(response.code()==200){
                        System.out.println("登录成功");
//                        System.out.println(response.body().string());
                        String result = response.body().string();
                        SharedPreferencesUtils.getInstance(LoginActivity.this).putString("username",username);
                        SharedPreferencesUtils.getInstance(LoginActivity.this).putString("password",password);
//                        System.out.println("fuck");
                        JSONObject jsonObject = new JSONObject(result);
                        SharedPreferencesUtils.getInstance(LoginActivity.this).putString("token",jsonObject.getString("token"));
                        SharedPreferencesUtils.getInstance(LoginActivity.this).putString("type",jsonObject.getString("type"));
                        Information();
                        //这里要看信息是否完整
                    }else{
                        System.out.println("登录失败");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(LoginActivity.this, "登录失败，快递员不存在或者密码错误",Toast.LENGTH_LONG).show();
                            }
                        });
                        SharedPreferencesUtils.getInstance(LoginActivity.this).putString("username","");
                        SharedPreferencesUtils.getInstance(LoginActivity.this).putString("password","");
                        SharedPreferencesUtils.getInstance(LoginActivity.this).putString("token","");
                        SharedPreferencesUtils.getInstance(LoginActivity.this).putString("type","");
                    }
                    response.body().close();
                }catch (JSONException je){
                    System.out.println("1"+je.getMessage().toString());
                }catch (Exception e){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(LoginActivity.this, "服务器连接失败,服务器已下线，当前服务器IP"+getString(R.string.baseUrl),Toast.LENGTH_LONG).show();
                        }
                    });
                    System.out.println("2"+e.getMessage().toString());
                }
            }
        }).start();

    }


    private void Information(){
        System.out.println("调用成功");
        new Thread(new Runnable() {
            @Override
            public void run() {
                String url = getString(R.string.baseUrl)+"/Information";
                System.out.println(url);
                final OkHttpClient client = new OkHttpClient();
                RequestBody body = RequestBody.create(null,"");
                System.out.println(body.toString());
                final Request request = new Request.Builder()
                        .url(url)
                        .addHeader("Authorization","Bearer "+SharedPreferencesUtils.getInstance(LoginActivity.this).getString("token", ""))
                        .post(body)
                        .build();
                try {
                    //判断请求是否成功，也就是判断登录是否成功
                    Response response = client.newCall(request).execute();
                    if(response.code()==200){
                       if(response.body().string().equals("success")){
                           //这里根据type选择要去的页面
                           String type = SharedPreferencesUtils.getInstance(LoginActivity.this).getString("type","");
                           if(type.equals("0")){
                               //服务器返回收件人是他的快递信息
                               //到收件人的页面
                               Intent i = new Intent(LoginActivity.this,CustomerMenu.class);
                               startActivity(i);
                           }else if(type.equals("1")){
                               //目前直接到创建订单页面
                               Intent i = new Intent(LoginActivity.this, SenderMenu.class);
                               startActivity(i);
                           }else if(type.equals("2")){
                               //获得
                               Intent i = new Intent(LoginActivity.this, DeliveryMenu.class);
                               startActivity(i);
                           }
                       }else{
                           Intent i = new Intent(LoginActivity.this,InformationActivity.class);
                           startActivity(i);
                           //去完善信息页面
                           //完善信息
                       }
                        LoginActivity.this.finish();
                    }else{
                        //这里是请求失败，不允许登录，将登陆信息消除，并返回
                        SharedPreferencesUtils.getInstance(LoginActivity.this).putString("username","");
                        SharedPreferencesUtils.getInstance(LoginActivity.this).putString("password","");
                        SharedPreferencesUtils.getInstance(LoginActivity.this).putString("token","");
                        //无法完善信息，并让用户重新登录
                    }
                    response.body().close();
                }catch (Exception e){
                    System.out.println(e.getMessage().toString());
                }
            }
        }).start();
    }


    private void register_go_help(){
        final SpannableStringBuilder style = new SpannableStringBuilder();
        //设置文字
        style.append("还未注册？点击这里注册");
        //设置部分文字点击事件
        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                Intent i = new Intent(LoginActivity.this,RegisterActivity.class);
                startActivity(i);
            }
        };
        style.setSpan(clickableSpan, 5, 9, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv.setText(style);
        //设置部分文字颜色
        ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.parseColor("#0000FF"));
        style.setSpan(foregroundColorSpan, 5, 9, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        //配置给TextView
        tv.setMovementMethod(LinkMovementMethod.getInstance());
        tv.setText(style);
    }
}